﻿package com.cilico.view;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;

import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextPaint;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

import com.cilico.ConfigManager;
import com.cilico.R;
import com.cilico.components.ChannelParam;
import com.cilico.components.Component;
import com.cilico.components.Alert;
import com.cilico.components.mButton;
import com.cilico.components.cCheckBox;
import com.cilico.components.ImageItem;
import com.cilico.components.Label;
import com.cilico.components.Radio;
import com.cilico.components.Select;
import com.cilico.components.StatusBar;
import com.cilico.components.TabItem;
import com.cilico.components.TabBar;
import com.cilico.components.TabBar.ContentLayout;
import com.cilico.components.Table;
import com.cilico.components.mTextField;
import com.cilico.components.mViewFlipper;
import com.cilico.components.POI;
import com.cilico.components.Paging;
import com.cilico.components.PoiListSelection;
import com.cilico.components.PoiRepository;
import com.cilico.components.PoiSelection;
import com.cilico.components.UploadFile;
import com.cilico.shopcart.ShopCartInfo;
import com.cilico.utils.Constant;
import com.cilico.utils.Utils;

public class DetailView extends BaseView {
	static final int COLLECTION = 0;
	static final int CHANNEL = 1;
	static final int CHANNEL_LIST = 0;
	static final int POI_LIST = 1;
	static final int POI_ONLY_ONE = 2; // POI列表只有一个
	static final int POI_DETAIL = 3;   // POI列表有多个
	public int detailType_; // type of current detail, the value is one of CHANNEL_LIST, POI_LIST, POI_DETAIL
	boolean isShowQueryView_;
	boolean isShowEntry_;
	boolean isRunChangeChannel_;
	private DetailController detailCtrl_;

	// special items for channel list and poi list.
	Label nextItem_; // 下一个Item
	Label prevItem_; // 上一个Item

	// Label adMobile_;
	private Label name_ = null;
	private Label phone_ = null;
	private Label url_ = null;
	Label showEntries_ = null;
	protected Vector<ImageItem> images_;
	private Vector<Label> extAttrs_; // List of extended attributes as ListItems
	POI currentDisplayPoi_; // 保存当前显示的POI，用于返回
	// 需要移动的内嵌scrollView
	public static LPLinearLayoutView scrollView_;
	// 触摸屏幕按下时的坐标
	int touchY_;
	
	// 当前频道id
	String channelID;
	String shopMode;
	public ArrayList <ShopCartInfo> shopCartList;
	
	// 用户头像
	public File picture;
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if (null != activities_) {
			activities_.add(this);
		}
		// 进入界面后立即复制当前界面对象，保存当前界面
		ConfigManager.currentView_ = this;
		// 设置按键响应监听
		/* initialize a DetailController */
		detailCtrl_ = new DetailController(this);
		setComponentLister(detailCtrl_);

		// 得到其他界面传递过来的值
		Bundle bundle = getIntent().getExtras();
		if (null != bundle) {
			showTab_ = bundle.getBoolean("showTab");
			isRunChangeChannel_ = bundle.getBoolean("isRunChangeChannel");
			isShowQueryView_ = bundle.getBoolean("isShowQueryView");
			detailType_ = bundle.getInt("detailType");
			channelID = (String) bundle.getCharSequence("channelID");
		}
		initScreenManager(this);
		setBackgroundResource(R.drawable.background, this, 3);
		this.setRightMenuMode(BaseView.NO_MENU, null);
		// 添加标题栏控件
		addTitleBar();
		titleBar_.setTitleAltText("");
		titleBar_.textColor_ = Utils.WHITE;
		// 添加状态栏
		createStatusBar();
		Paint boldFont = new Paint();
		boldFont.setTypeface(Typeface.DEFAULT_BOLD);
		boldFont.setTextSize(ConfigManager.SIZE_SMALL);

		Paint f = new Paint();
		f.setTypeface(Typeface.DEFAULT);
		f.setTextSize(Utils.getScaledValue(ConfigManager.SIZE_SMALL));

		/* initialize channel list and poi list special items. */
		nextItem_ = new Label(this, getString(R.string.nextPage), false, true, true);
		nextItem_.setWidth(Component.MAX_WIDTH);

		prevItem_ = new Label(this, getString(R.string.prevPage), false, true, true);
		prevItem_.setWidth(Component.MAX_WIDTH);

		/* initialize poi detail special items. */
		name_ = new Label(this, "", false, true, true);
		name_.textColor_ = Utils.WHITE;
		phone_ = new Label(this, "", true, true, true);
		url_ = new Label(this, "Read More", true, true, true);
		showEntries_ = new Label(this, "Show entries", true, true, true);
		BackGroundColor_ = Utils.BLACK;
		boolean hiddenWaitDialog = show();

		// 将中间布局管理器布局方式设置为靠上
		if (hiddenWaitDialog) {
			Utils.addManagerAndSetTop(this);
		} else {
			show(this);
            tabBar_.setGravity(Gravity.TOP);
            tabBar_.setContentLayoutGravity();
		}
	}
	
	
	/**
	 * 创建状态栏
	 */
	protected void createStatusBar() {
		if (null == mid_)
			return;
		Vector<String> menuV = mid_.um_.menuV_;
		int size = 0;
		if (menuV != null)
			size = menuV.size();
		// 在状态栏加一个首页图标
		size += 1;
		Bitmap mainIcon;
		Bitmap mainIconD;
		
		if (labels_ == null || labels_.length != size) {
			releaseSource();
			labels_ = new String[size];
			bitmaps_ = new Bitmap[size];
			bitmapsD_ = new Bitmap[size];
			StatusBar.ARRVALUE = new String[size];
			
			Bitmap customImgMini = mid_.constant_.getChannelIconMini(Constant.DEFAULT_CHANNEL_SHORTCUT_MINI);
			Bitmap customImgMiniSelected = mid_.constant_.getFocusChannelIcon(Constant.DEFAULT_CHANNEL_SHORTCUT_MINI);
	
			for (int i = 0; i < size; i++) {
				if (i == 0) {
					labels_[i] = Constant.FIRSTPAGE;
					bitmaps_[i] = mid_.constant_.getChannelIconMini(Constant.FIRSTPAGE);
					bitmapsD_[i] = mid_.constant_.getFocusChannelIcon(Constant.FIRSTPAGE);
				} else {
					String shortCut = (String) menuV.elementAt(i - 1);
					Channel ch = mid_.channelRepo_.getChannelByShortCut(shortCut);
					if (ch != null) {
						labels_[i] = mid_.constant_.fitText(ch.title());
						StatusBar.ARRVALUE[i] = ch.id();
						String str = ConfigManager.mainMenuShortCut_[getIndex(ch.shortCut_)];
						mainIcon = mid_.constant_.getChannelIconMini(str);
						mainIconD = mid_.constant_.getFocusChannelIcon(str);
						bitmaps_[i] = mainIcon != null ? mainIcon : customImgMini;
						bitmapsD_[i] = mainIconD != null ? mainIconD : customImgMiniSelected;
						
					}
				}
			}
		}
		
		initStatuwBar(labels_, bitmaps_, bitmapsD_);
	}
	
	protected void initchaneltitle() {
		if (null == mid_)
			return;
		Vector<String> menuV = mid_.um_.menuV_;
		int size = 0;
		if (menuV != null)
			size = menuV.size();
		// 在状态栏加一个首页图标
		size += 1;
		
		if (labels_ == null || labels_.length != size) {
			releaseSource();
			labels_ = new String[size];
			StatusBar.ARRVALUE = new String[size];
			
			for (int i = 0; i < size; i++) {
				if (i == 0) {
					labels_[i] = Constant.FIRSTPAGE;
				} else {
					String shortCut = (String) menuV.elementAt(i - 1);
					Channel ch = mid_.channelRepo_.getChannelByShortCut(shortCut);
					if (ch != null) {
						labels_[i] = mid_.constant_.fitText(ch.title());
					}
				}
			}
		}
	}
	
	private void initStatuwBar(String[] labels, Bitmap[] bitmaps, Bitmap[] bitmapsD) {
		statusBar_ = new StatusBar(this, labels, bitmaps, bitmapsD);
		if (llDown_ != null){
			llDown_.removeAllViews();
		}
		llDown_.addView(statusBar_);
	}
	

	/**
	 * 获取字符串在数组中的下标
	 * */
	private int getIndex (String str) {
		for (int i = ConfigManager.mainMenuShortCut_.length - 1; i >= 0; i--) {
			if (str.contains(ConfigManager.mainMenuShortCut_[i])) {
				return i; 
			}
		}
		return 0;
	}
	
	private void releaseSource() {
		if (labels_ != null) {
			for (int i = labels_.length - 1; i >= 0; i--) {
				bitmaps_[i].isRecycled();
				bitmapsD_[i].isRecycled();
				labels_[i] = null;
				bitmaps_[i] = null;
				bitmapsD_[i] = null;
			}
			labels_ = null;
			bitmaps_ = null;
			bitmapsD_ = null;
			statusBar_ = null;
			System.gc();
		}
		if (labels_1 != null){
			for (int i = labels_1.length - 1; i >= 0; i--) {
				bitmaps_1[i].isRecycled();
				bitmapsD_1[i].isRecycled();
				labels_1[i] = null;
				bitmaps_1[i] = null;
				bitmapsD_1[i] = null;
			}
			labels_1 = null;
			bitmaps_1 = null;
			bitmapsD_1 = null;
			statusBar_ = null;
			System.gc();
		}
		
	}
	
	private void addTitleBarButton() {
		// TODO Auto-generated method stub
		// 改变添加返回首按钮标志
		if (null != this.titleBar_) {
			if (null != leftMenuText_) {
				this.titleBar_.showBack_ = true;
				this.titleBar_.backText_ = leftMenuText_;
			} else {
				this.titleBar_.showBack_ = false;
				this.titleBar_.backText_ = "";
			}

			// 改变添加返回首页按钮标志
			PoiSelection poiSel = mid_.getCurrentPoiSelection(false, this);
			if (detailType_ == CHANNEL_LIST) {
				this.titleBar_.showHeader_ = true;
			} else if (detailType_ == POI_LIST) {
				this.titleBar_.showHeader_ = true;
			} else if (detailType_ == POI_ONLY_ONE || detailType_ == POI_DETAIL) {
				if (!isShowQueryView_) {
					if (poiSel instanceof PoiListSelection) {
						this.titleBar_.showHeader_ = true;
					}
				}
			}

		}
	}

	/**
	 * 当屏幕横竖切换时调用此方法
	 * */
	public void onConfigurationChanged(Configuration newConfig) {
		llUp_.removeAllViews();
		int roientation = this.getResources().getConfiguration().orientation;
		// 横竖屏切换时调用此方法交换宽高
		changeScreenWidthHeight(roientation);
		// delete titleBar!!!
		titleBar_.setWidth(Utils.screenWidth_);
		llUp_.addView(titleBar_);
		if (tabBar_.tab_.isShown()) {
			// 重新定位及布局tab
			TabItem.changeTabSize(tabBar_.tab_, Constant.backgroundTab_);
			TabItem.changeTabSize(statusBar_.t_, Constant.statusBackground_);
		}

		// 这里必须调用父类的onConfigurationChanged方法，否则报异常
		super.onConfigurationChanged(newConfig);
	}


	private void adjustQueryViewMenu() {
		setRightMenuMode(BaseView.OTHER_MENU, getString(R.string.search));
	}

	/**
	 * Interrupted loading Image when we move out the detail screen.
	 */
	protected void interruptLoadImage(POI poi) {
		if (poi.images_.size() < poi.totalImages_)
			poi.isInterrupteLoad_ = true;
	}


	void setDefaultMenu() {

	}
	
	boolean populate(Object poi) {
		if (showTab_) {
			appendTabBar(this);

			setSubmenuContents();

			return isTopChannelAlone();
		} else {
			removeTabBar();
			setShowDetail((POI) poi);
		}
		return true;
	}

	// 设置二级界面内容,包括现实控件和titlebar上的按钮显示
	private void setSubmenuContents() {
		// TODO Auto-generated method stub
		setTabbarContents();
		// 缓存中有内容，表示该界面不是主界面后的第一级界面，此时应在titlebar上加上返回按钮
		setLeftMenuMode(BaseView.BACK_MENU);
		if (null != this.titleBar_)
			titleBar_.invalidate();
		addTitleBarButton();
	}

	/**
	 * 判断topChannel是否只有一个元素，如果是就直接模拟点击效果进入poi界面
	 */
	private boolean isTopChannelAlone() {
		// TODO Auto-generated method stub
		final int size = mid_.topChannelRepo_.getSize();
		if (size <= 0) {
			
		} else if (size == 1) {
			mButton button = (mButton) this.tabBar_.getContentLayout().getChildAt(0);
			button.isTopChannelAlone_ = true;
			button.pointerPressed(this);
			return false;
		} else {
			// 二级界面用字符组压栈压栈
			mid_.poiRepo_.pushActionPoi(mid_.topChannelRepo_.getChannelTitles());
		}
		return true;
	}

	/**
	 * Set the contents of the tab bar.
	 */
	private void setTabbarContents() {
		try {
			String[] labels = null;
			String[] icons = null;
			labels = mid_.topChannelRepo_.getChannelTitles();
			icons = mid_.topChannelRepo_.getIconNames();
			final int sizeLabels = labels.length;
			boolean firstSubmenu = false;
			boolean lastSubmenu = false;
			for (int i = 0; i < sizeLabels; i++) {
				if (i == 0) {
					firstSubmenu = true;
				} else if (i == sizeLabels - 1) {
					lastSubmenu = true;
				}
				mButton button = new mButton(DetailView.this, labels[i], -1, true,	firstSubmenu, lastSubmenu);
				if (null != icons[i] && icons[i].length() > 0){
					button.setIcons(icons[i]);
				}
				firstSubmenu = false;
				// label.setComponentLister(dtCtl_);
				appendAtFixP(button);
			}
			// tabBar_.addTab(this, labels, null, MapView.activeTab_,
			// MapView.inactiveTab_);
			// tabBar_.setComponentLister(dtCtl_);
			// tabBar_.tab_.setCurrentTab(mid_.topChannelRepo_
			// .getCurrentChannelIndex());
			// tabBar_.reculculateMaxUnitNum();
			// resetDetailType();
		} catch (Exception ex) {
			Utils.printException(ex);
		}

	}

	private void appendTabBar(BaseView bv) {
		/* add tabber. */
		// tabBar_.left_ = 0;
		// tabBar_.top_ = titleBar_.top_ + titleBar_.height_;
		tabBar_.hasBorder_ = true;
		tabBar_.setBgColor(Utils.TABBARBACKGROUNDCOLOR);
		tabBar_.setBorderColor(Utils.WHITE);
		tabBar_.textColor_ = Utils.WHITE;
	}

	final void changePage(boolean isForward) {
		Paging pg = null;
		if (detailType_ == CHANNEL_LIST) {
			pg = getChannelListPaging();
		} else if (detailType_ == POI_LIST) {
			pg = getPoiListPaging();
		}
		if (isForward) {
			pg.nextPage();
		} else {
			pg.prevPage();
		}
	}

	void resetDetailType(DetailView bv) {
		bv.detailType_ = DetailView.POI_ONLY_ONE;
	}

	void setShowDetail(final POI poi) {
		removeCountLabel();
		removeAll();
		// 缓存中有内容，表示该界面不是主界面后的第一级界面，此时应在titlebar上加上退回按钮
		setLeftMenuMode(BaseView.BACK_MENU);
		addTitleBarButton();
		showBackGround_ = false;
		if (isShowQueryView_) {
			detailType_ = POI_ONLY_ONE;
		}
		try {
			// 设置左边菜单命令为“菜单”
			setRightMenuMode(BaseView.OPTIONS_MENU, null);
			if (null != mid_.getCurrentPoiSelection(false, DetailView.this)) {
				if (detailType_ == POI_LIST && mid_.getCurrentPoiSelection(false, DetailView.this).size() <= 1
						&& getPoiListPaging().lastPage_ == 1) { // poi list but only one
					detailType_ = POI_ONLY_ONE;
				}
			}

			if (detailType_ == CHANNEL_LIST) { // channel list
				String[] chanelTitles = mid_.belowChannelRepo_.getChannelTitles();
				final int sizeChanelTitles = chanelTitles.length;
				for (int i = 0; i < sizeChanelTitles; i++) {
					Label label = new Label(DetailView.this, chanelTitles[i], false, true, true);
					label.setWidth(Component.MAX_WIDTH);
					// label.setComponentLister(dtCtl_);
					label.textColor_ = Utils.WHITE;
					appendAtFixP(label);
				}
				addPageCommands();
			} else if (detailType_ == POI_LIST) { // poi list
				PoiSelection poiSel = mid_.getCurrentPoiSelection(false, DetailView.this);
				PoiRepository r = poiSel.poiRepo_;
				POI[] pois = poiSel.getSelectedPOIs();
				int sz = 0;
				if (pois != null) {
					sz = pois.length;
				}
				for (int i = 0; i < sz; i++) {
					final Label label = new Label(DetailView.this, (i + 1) + "." + pois[i].name(), false, true, true);
					label.setWidth(Component.MAX_WIDTH);
					// label.setComponentLister(dtCtl_);
					append(label);
					appendAtFixP(label);
				}
				addPageCommands();
			} else if (detailType_ == POI_ONLY_ONE || detailType_ == POI_DETAIL) { // poi detail.
				if (isShowQueryView_) { // query view.
					setQueryContents();
					adjustQueryViewMenu();
				} else {
					PoiSelection poiSel = mid_.getCurrentPoiSelection(false, DetailView.this);
					int index = poiSel.getCurrentDisplayIndex() - 1;
					if (index < 0 || index > poiSel.size() - 1) {
						index = 0;
					}
					DisplayPoi disPoi = (DisplayPoi) poiSel.elementAt(index);
					if (disPoi != null) {
						poiSel.setCurrentDisplayIndex(disPoi.getDisplayIndex());
						mid_.checkUpdatesFromServer(mid_.getCurrentPoiSelection(false, DetailView.this), DetailView.this);
					}
					disPoi = poiSel.getCurrentPOI();
					if (poiSel instanceof PoiListSelection) {
						setPOIDetailContents(disPoi, poi);
					}
				}
				currentItem_ = -1;
				if (tabBar_ != null) {
					tabBar_.focus_ = true;
				}
			}
		} catch (Exception ex) {
			setDefaultMenu();
			Utils.printException(ex);
		}

		if (countLabel_ != null && countLabel_.delaytime_ > 0) {
			if (countTimer_ != null) {
				countTimer_.cancel();
				countTimer_ = null;
			}
			StringBuffer sb = new StringBuffer(countLabel_.getText());
			char c = sb.charAt(Integer.parseInt(countLabel_.offset_));
			if (c > '9' || c < '0') {
				sb.insert(Integer.parseInt(countLabel_.offset_), countLabel_.delaytime_);
			}
			countLabel_.setText(sb.toString());
			countTimer_ = new Timer();
			countTimer_.schedule(new TimerTask() {
				public void run() {
					countDownTime();
				}
			}, 0, 1000);
		}
	}

	/**
	 * 倒计时计算
	 * */
	void countDownTime() {
		if (countLabel_ == null) {
			countTimer_.cancel();
			return;
		}
		if (countLabel_.delaytime_ >= 0) {
			StringBuffer sb = new StringBuffer(countLabel_.getText());
			sb.deleteCharAt(Integer.parseInt(countLabel_.offset_));
			sb.insert(Integer.parseInt(countLabel_.offset_), countLabel_.delaytime_);
			countLabel_.delaytime_--;
			countLabel_.setText(sb.toString());
		} else {
			int size = tabBar_.getContentChildCount();
			for (int i = 0; i < size; i++) {
				View cmp = (View) tabBar_.getContentChild(i);
				if (cmp instanceof mButton) {
					if (((mButton) cmp).getText().equals(getString(R.string.sure)))
						cmp.setEnabled(false);
				}
			}
			countLabel_.offset_ = null;
			countLabel_.setText(countLabel_.caption_);
			// reCalculateTotalWH();
			countTimer_.cancel();
		}
	}

	private void setPOIDetailContents(final DisplayPoi disPoi, final POI referPoi) throws Exception {
		POI poi = referPoi;
		if (referPoi == null && disPoi != null) {
			poi = disPoi.poi_;
		}
		currentDisplayPoi_ = poi;
		if (poi == null)
			return;
		// append poi name on the top.
		StringBuffer name = new StringBuffer();
		if (disPoi != null && (detailType_ != POI_ONLY_ONE)) {
			name.append(disPoi.getDisplayIndex());
			name.append(". ");
		}
		if (poi.name() != null)
			name.append(poi.name());
		if (name.length() > 0 && (detailType_ != POI_ONLY_ONE)) {
			name_.setText(name.toString());
			name_.focus_ = false;
			append(name_);
			appendAtFixP(name_);
		}

		if (poi.totalImages_ > 0) {
			poi.CalculateImgSize();
			images_ = new Vector<ImageItem>();
			for (int i = 0; i < poi.totalImages_; i++) {
				ImageItem image = new ImageItem(DetailView.this);
				if (poi.imgUrls_.elementAt(i) != null && i >= poi.images_.size()) {
					// 该处为图片为下载完成时添加正在载入效果图片
					image.setImage(Utils.createImgWaitLoad(mid_, null, 0x88888888, 0, 0));
				} else {
					image.setImage((Bitmap) poi.images_.elementAt(i));
				}
				String link = null;
				link = (String) poi.imgLinks_.elementAt(i);
				if (link == null) {
					link = (String) poi.imgUrls_.elementAt(i);
				}
				image.setUrl(link);
				images_.insertElementAt(image, i);
			}
		}

		if (poi.phone_ != null) {
			StringBuffer number = getPhoneNumber(poi.phone_, "");
			if (number.length() >= 7) {
				phone_.setText(poi.phone_);
				phone_.focus_ = false;
				append(phone_);
				appendAtFixP(phone_);
			}
		}
		int numExtAttr = poi.eattrNames_.size();
		if (numExtAttr > 0) {
			int oldSize = extAttrs_.size();
			int i;
			Label item = null;
			for (i = 0; i < oldSize; ++i) {
				item = extAttrs_.elementAt(i);
				if (i % 2 == 0) {
					item.setText((String) poi.eattrNames_.elementAt(i));
				} else {
					item.setText((String) poi.eattrValues_.elementAt(i));
				}
				item.setWidth(Component.MAX_WIDTH);
				append(item);
				appendAtFixP(item);
			}
			for (i = oldSize; i < numExtAttr; ++i) {
				if ((i - oldSize) % 2 == 0) {
					item = new Label(DetailView.this, (String) poi.eattrNames_.elementAt(i), false, false, false);
				} else {
					item = new Label(DetailView.this, (String) poi.eattrValues_.elementAt(i), false, false, false);
				}
				item.setWidth(Component.MAX_WIDTH);
				append(item);
				appendAtFixP(item);
				extAttrs_.addElement(item);
			}
		}

		try {
			Utils.parseUsingkXML(poi.desc_, DetailView.this);
		} catch (Exception e) {
			Utils.printException(e);
		}

		// Link to the URL of the detail of this POI.
		if (poi.url_ != null && poi.url_.length() > 0) {
			url_.focus_ = false;
			append(url_);
			appendAtFixP(url_);
		}

		if (poi.showEntryUrl_ != null && poi.showEntryLen_ > 0) {
			showEntries_.focus_ = false;
			append(showEntries_);
			appendAtFixP(showEntries_);
		}
	}

	private static StringBuffer getPhoneNumber(String text, String init) {
		char[] str = text.toCharArray();
		StringBuffer number = new StringBuffer(init);
		for (int i = 0; i < str.length; ++i) {
			if (str[i] >= '0' && str[i] <= '9')
				number.append(str[i]);
		}
		return number;
	}

	private void setQueryContents() {
		tabBar_.removeAllContentChild();
		Channel queryCh_ = mid_.poiRepo_.channel_;
		Vector<ChannelParam> pv = queryCh_.params();
		int endParam_ = -1;
		TextPaint font = new TextPaint();
		font.setTypeface(Typeface.DEFAULT_BOLD);
		font.setTextSize(Utils.getScaledValue(ConfigManager.SIZE_SMALL));
		for (int i = 0; i < pv.size(); ++i) {
			endParam_ += insertItem(font, (ChannelParam) pv.elementAt(i));
		}
		showBackGround_ = false;
		mid_.channelEntity_.backfill(this);
	}

	private final int insertItem(TextPaint font, ChannelParam p) {
		int qnum = 0;
		String type = ((p.type_ == null) ? "" : p.type_);
		if (!type.equals("label")) {
			String labelStr = (p.label_ == null) ? p.name_ : p.label_.concat(":");
			if (((null == labelStr) || (labelStr.equalsIgnoreCase(""))) && type.equals("text")) {
				labelStr = getString(R.string.pleaseInput);
			}
			if (labelStr != null) {
				Label temp = new Label(this, labelStr, false);
				this.appendAtFixP(temp);
			}
		}
		if (type.equals("text")) {
			// XXX max length 1024 is rather arbitrary!
			mTextField item = new mTextField(this, (p.label_ == null) ? p.name_ : p.label_, p.placeholder_, null, false, 64, 0, 0, true);
			item.setWidth(Component.MAX_WIDTH);
			item.setTextColor(Utils.BLACK);
			item.setHint(ConfigManager.DEFAULTTEXT);
			if (p.value_ != null)
				item.setText(p.value_);
			else
				item.setText("");
			item.attrName_ = p.name_;
			append(item);
			this.appendAtFixP(item);
			qnum += 1;
		} else if (type.equals("checkbox")) {
			cCheckBox item = new cCheckBox(this, ((p.label_ == null) ? p.name_ : p.label_));
			item.setTextColor(Utils.WHITE);
			item.setChecked(p.isChecked_);
			append(item);
			this.appendAtFixP(item);
			qnum += 1;
		} else if (type.equals("radio")) {
			Radio item = new Radio(this, ((p.label_ == null) ? p.name_ : p.label_), font, p.name_, p.selectSort_,
					p.sortKey_);
			item.setTextColor(Utils.WHITE);
			append(item);
			this.appendAtFixP(item);
			if (getSelectRadio(this, item) == null) {
				item.setChecked(true);
				// if there is not any selected we set current as default.
			} else {
				item.setChecked(p.isChecked_);
			}
			qnum += 1;
		} else if (type.equals("select")) {
			int num = p.valuesV_.size();
			final Select item = new Select(this, ((String) p.valuesV_.firstElement()));
			Select.textColor_ = Utils.WHITE;
			for (int i = 0; i + 1 < num; i += 2) {
				String text = (String) p.valuesV_.elementAt(i);
				item.setDropdownMenuText(text);
				String value = (String) p.valuesV_.elementAt(i + 1);
				if (value.equals(p.value_)) {
					item.setText(text);
					item.setCurrentMenu(i >> 1);
					item.settleRelationAction();
				}
			}
			append(item);
			this.appendAtFixP(item);
			qnum += 1;
		} else if (type.equals("label")) {
			String lb = (p.label_ == null) ? p.name_ : p.label_;
			if (lb != null)
				lb += ":";
			Label lbItem = new Label(this, lb, false, false, false);
			lbItem.textColor_ = Utils.WHITE;
			// lbItem.setFont(font);
			lbItem.setWidth(Component.MAX_WIDTH);
			lbItem.isTagParse_ = true;
			append(lbItem);
			this.appendAtFixP(lbItem);
		}
		return qnum;
	}

	private final void addPageCommands() {
		Paging pg = null;
		if (detailType_ == CHANNEL_LIST) {
			pg = getChannelListPaging();
		} else if (detailType_ == POI_LIST) {
			pg = getPoiListPaging();
		}
		if (pg == null) {
			return;
		}
		if (!pg.atEnd() && pg.lastPage_ > pg.currentPage_) {
			append(nextItem_);
			this.appendAtFixP(nextItem_);
			nextItem_.setOnClickListener(new View.OnClickListener() {

				public void onClick(View arg0) {
					currentItem_ = DetailView.this.tabBar_.indexOfContentChild(arg0);
					nextItem_.pointerPressed(DetailView.this);
				}
			});
		}
		if (!pg.atStart()) {
			append(prevItem_);
			this.appendAtFixP(prevItem_);
			prevItem_.setOnClickListener(new View.OnClickListener() {

				public void onClick(View arg0) {
					currentItem_ = DetailView.this.tabBar_.indexOfContentChild(arg0);
					prevItem_.pointerPressed(DetailView.this);
				}
			});
		}
	}

	public void showTab(boolean b) {
		showTab_ = b;
	}

	public boolean show() {
		if (mid_.waitDialog_.getDisplayTaskStatus()) {
			mid_.poiRepo_.popActionPoi();
			return true;
		}
		return populate(mid_.poiRepo_.popActionPoi());
	}

	Paging getPoiListPaging() {
		return mid_.getCurrentPoiSelection(false, this).getPaging();
	}

	Paging getChannelListPaging() {
		return mid_.belowChannelRepo_.getPaging();
	}

	@Override
	public void dealWithLink(String link, BaseView bv, Boolean bl) {
		if (link != null) {
			link = link.trim();
			//此处点击编辑按钮后再点击图片时发送的请求与之前点击图片进入详细页面的请求是不一样的
			if (link.startsWith("lp:")) {
				String url = "http" + link.substring(2);
				String body = null;
				int index = url.indexOf("?");
				if (index != -1) {
					body = url.substring(index + 1);
					url = url.substring(0, index);
				}
				// add _s for the controllers.
				Channel ch = mid_.topChannelRepo_.getCurrentChannel();
//				if (ch.isSecure_) {
				String temphost = null;
				int indexC = url.indexOf("/channel/");
				int indexA = url.indexOf("/atompub/");
				if (indexC != -1) {
					temphost = url.substring(0, indexC) + "/channel_s/" + url.substring(indexC + "/channel/".length());
				} else if (indexA != -1) {
					temphost = url.substring(0, indexA) + "/atompub_s/" + url.substring(indexA + "/atompub/".length());
				}
				if (temphost != null)
					url = temphost;	
				Utils.printOutToConsole("--- dealWithLink() +++ body:\n" + body);
				mid_.channelEntity_.loadLinkContent(url, body, bv);
			} else if (link.startsWith("channel:")) {
				// URL syntax: channel://host/atompub/chlink/channel_id? or URL
				// syntax: channel://host/atompub/chlink/channel_id/...?
				final String chform = "chlink/";
				int id1 = link.indexOf(chform);
				int id2 = -1;
				int tmp = link.indexOf('/', id1);
				int tmp1 = link.lastIndexOf('/');
				if (tmp == tmp1) {
					id2 = link.indexOf("?", id1 + chform.length());
				} else {
					id2 = tmp1;
				}
				String channelId = null;
				channelId = link.substring(id1 + chform.length(), id2);

				String url = "http" + link.substring(7);
				String body = null;
				int index = url.indexOf("?");
				if (index != -1) {
					body = url.substring(index + 1);
					url = url.substring(0, index);
				}
				// add _s for the controllers.
				// channel 跳转时改成全部加密。
				// Channel ch = mid_.topChannelRepo_.getCurrentChannel();
				// if (ch.isSecure_) {
				String temphost = null;
				int indexC = url.indexOf("/channel/");
				int indexA = url.indexOf("/atompub/");
				if (indexC != -1) {
					temphost = url.substring(0, indexC) + "/channel_s/" + url.substring(indexC + "/channel/".length());
				} else if (indexA != -1) {
					temphost = url.substring(0, indexA) + "/atompub_s/" + url.substring(indexA + "/atompub/".length());
				}
				if (temphost != null)
					url = temphost;
				Utils.printOutToConsole("body ==== " + body);
				mid_.channelEntity_.switchChannel(bv, channelId, false, url, body, false);
			} else if (link.startsWith("showBranch:/")) {
				POI p = currentDisplayPoi_;
				mid_.poiRepo_.entryUrl_ = ConfigManager.SERVER_URI + link.substring(12);
				mid_.channelEntity_.loadContentEntry(p, bv);
			} else if (link.startsWith("local://")) {
				// 本地页面
				mid_.channelEntity_.goToLocalPage(link, bv);
			} else {
				super.dealWithLink(link, bv, false);
			}
		}
	}


	/**
	 * When we go back we should re-set current item to be the current channel.
	 */
	public void keyBackPressed() {
		if (istimeout_){
//			mid_.getCurrentPoiSelection(false, DetailView.this).poiRepo_.actionV_.removeAllElements();
			Alert.exitSystem(this);
			return;
		}
		BaseView.ttimerIscannel_ = true;
		if (Table.tableTimer_ != null) {
			Table.tableTimer_.cancel();
			Table.tableTimer_ = null;
		}
		if (mViewFlipper.imgsTimer_ != null){
			mViewFlipper.imgsTimer_.cancel();
			mViewFlipper.imgsTimer_ = null;
		}
		hideSoft();
		Select.ISRUNNING = false;
		// 当界面上有tabbar控件显示时，先取消相关控件的显示效果
		View tabTemp = this.tabBar_.llH_.getChildAt(0);
		if (null != tabTemp) {
			if (tabTemp.isShown()) {
				tabTemp.setVisibility(View.GONE);
				this.statusBar_.setVisibility(View.GONE);
				// ((ImageView) (this.tabBar_.llH_.getChildAt(1))).setImageResource(R.drawable.show_btn);
				return;
			}
		}

		View view = popContentStack();
		if (view != null) {
			resetMiddlePanel(view, false);
			if (isContentStackEmpty()) {
				isInCeAirCjrLxrDiv_ = false;
			}
		} else if (detailType_ == POI_DETAIL) {
			POI p = (POI) mid_.poiRepo_.popActionPoi();
			DisplayPoi dp = mid_.getCurrentPoiSelection(false, this).getCurrentPOI();
			if (p != null) {
				setShowDetail(p);
			} else if (!mid_.channelEntity_.isCurrentQueryChannel() && dp != null && dp.poi_ != null
					&& dp.poi_ != currentDisplayPoi_) {
				if (blackView_ == 3) {
					blackView_ = 0;
					mid_.channelEntity_.updateBelowPOIList();
				} else {
					populate(dp.poi_);
					Utils.addManagerAndSetTop(this);
				}
			} else {
				detailType_ = POI_LIST;
				if (!isShowEntry_) { // It means that NOW we are in the normal
					// detail view.
					mid_.poiRepo_.channel_.paging_.setCurrentPage(mid_.poiRepo_.showEntryParentPage_);
					mid_.channelEntity_.resetBelowPOIList(dp, this);
					mid_.poiRepo_.showEntryParent_ = null;
				} else { // It means that NOW we are in the detail view of show
					// entry and the current poi repository is SURELY
					// the show entry poi list.
					setShowDetail(null);
					// 显示从POI_DETALL界面返回到POI_LIST的界面
					Utils.addManagerAndSetTop(this);
				}
			}
		} else if (detailType_ == POI_ONLY_ONE) {
			Object o = mid_.poiRepo_.popActionPoi();
			if (o != null && o instanceof POI && ((POI) o).skip_2 && ((POI) o).skip_number != null){
				int temp = Integer.parseInt(((POI) o).skip_number.replace("skip_number_", ""));
				if (mid_.poiRepo_.actionV_.size() >= temp){
					for(int i=0;i<temp;i++){
						mid_.poiRepo_.popActionPoi();
					}
				}
			}
			o = mid_.poiRepo_.peekActionPoi();
			if (o instanceof POI && ((POI)o).popStack_) {
				mid_.poiRepo_.popActionPoi();
				o = mid_.poiRepo_.peekActionPoi();
			}  
			if (o instanceof String[]) {
				// 当栈内容不是poi的时候走该分支
				removeCountLabel();
				removeAll();
				String[] labels = null;
				labels = mid_.topChannelRepo_.getChannelTitles();
				if (labels.length == 1) {
					// 如果二级界面子菜单只存在一个子元素,则直接跳转至主界面
					mid_.channelEntity_.stepUpDetailView(this);
				} else {
					BaseView.updateTable_ = false;//此时是返回二级菜单，不走解析流程，所以要把此标记恢复，否则无法显示二级菜单！
					setSubmenuContents();
					Utils.isbackcompleted_ = true;
					// 该赋值涉及到在二级菜单界面返回后再进入的流程问题
					detailType_ = DetailView.CHANNEL_LIST;
					mid_.poiRepo_.poiXML_ = null;
				}
			} else {
				final POI p = (POI) o;
				if (p != null) {
					if (blackView_ == 3) {
						blackView_ = 0;
						if (mid_.topChannelRepo_.getSize() > 1) {
							for (int poiSize = mid_.poiRepo_.actionV_.size() - 1; poiSize > 0; poiSize--) {
								mid_.poiRepo_.popActionPoi();
							}
						} else 
							mid_.poiRepo_.removeAllActionPoi();
						mid_.channelEntity_.updateBelowPOIList();
						return;
					}
					mid_.waitDialog_.setDisplayTaskStatus(false);
					// 先显示进度条，然后延迟XX时间执行联网更新操作，否则进度条无法显示出来
					mid_.waitDialog_.showProgressdialog(this);
					new Timer().schedule(new TimerTask() {

						public void run() {
							DetailView.this.setShowDetail(p);
							Utils.addManagerAndSetTop(DetailView.this);
						}
					}, 600);

				} else if (isShowEntry_) {
					try {
						mid_.poiRepo_.parsePOIs(mid_.poiRepo_.channel_, mid_.poiRepo_.poiXML_);
					} catch (Exception ex) {
						Utils.printException(ex);
					}
					mid_.getCurrentPoiSelection(false, this).populate(mid_.poiRepo_);
					if (mid_.getCurrentPoiSelection(false, this).size() <= 1 && getPoiListPaging().lastPage_ == 1) { // poi列表数量为1
						detailType_ = POI_ONLY_ONE;
					} else {
						detailType_ = POI_DETAIL;
					}
					setShowDetail(mid_.poiRepo_.showEntryParent_);
					Utils.addManagerAndSetTop(this);
					isShowEntry_ = false;
				} else if (mid_.channelEntity_.isCurrentQueryChannel() && !isShowQueryView_) { // comes back to query view if it is in result view.
					detailType_ = POI_DETAIL;
					isShowQueryView_ = true;
					setShowDetail(null);
					Utils.addManagerAndSetTop(this);
				} else if (!mid_.channelEntity_.isCurrentQueryChannel()) {
					PoiSelection ps = null;
					DisplayPoi dpTemp = null;
					if (null != mid_.getCurrentPoiSelection(false, this)) {
						ps = mid_.getCurrentPoiSelection(false, this);
					}
					if (null != ps) {
						dpTemp = ps.getCurrentPOI();
					}
					final DisplayPoi dp = dpTemp;
					if (dp != null && dp.poi_ != currentDisplayPoi_) {
						if (blackView_ == 3) {
							blackView_ = 0;
							mid_.channelEntity_.updateBelowPOIList();
						} else {
							// 先显示进度条，然后延迟XX时间执行联网更新操作，否则进度条无法显示出来
							mid_.waitDialog_.showProgressdialog(this);
							new Timer().schedule(new TimerTask() {
								public void run() {
									populate(dp.poi_);
									Utils.addManagerAndSetTop(DetailView.this);
								}
							}, 600);
						}
					} else {
						mid_.channelEntity_.stepUpDetailView(this);
					}
				} else {
					mid_.channelEntity_.stepUpDetailView(this);
				}
			}
		} else if (detailType_ == POI_LIST) {
			if (isShowEntry_) {
				try {
					mid_.poiRepo_.parsePOIs(mid_.poiRepo_.channel_, mid_.poiRepo_.poiXML_);
				} catch (Exception ex) {
					Utils.printException(ex);
				}
				mid_.getCurrentPoiSelection(false, this).populate(mid_.poiRepo_);
				if (mid_.getCurrentPoiSelection(false, this).size() <= 1 && getPoiListPaging().lastPage_ == 1) { // poi list but only one
					detailType_ = POI_ONLY_ONE;
				} else {
					detailType_ = POI_DETAIL;
				}
				setShowDetail(mid_.poiRepo_.showEntryParent_);
				Utils.addManagerAndSetTop(this);
				isShowEntry_ = false;
			} else if (mid_.channelEntity_.isCurrentQueryChannel() && !isShowQueryView_) { // comes back to query view if it is in result view.
				detailType_ = POI_DETAIL;
				isShowQueryView_ = true;
				setShowDetail(null);
				Utils.addManagerAndSetTop(this);
			} else {
				mid_.channelEntity_.stepUpDetailView(this);
			}
		} else {
			mid_.channelEntity_.stepUpDetailView(this);
		}
	}

	// 按键操作
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			if(Utils.isbackcompleted_ ) {
				Utils.isbackcompleted_ = false;
				keyBackPressed();
			}
			break;
		default:
			return super.onKeyDown(keyCode, event);
		}
		return true;
	}

	void keyActionSoftKey() {
		String history = null;
		Channel queryCh_ = mid_.poiRepo_.channel_;
		queryCh_.resetPaging();
		try {
			if (currentItem_ - 2 >= 0 && queryCh_.numParams() == 1) {
				Label lb = (Label) ((ViewGroup) tabBar_.getContentLayout()).getChildAt(currentItem_);
				history = lb.getText().toString();
			}
		} catch (Exception e) {
			Utils.printException(e);
		}
		mid_.channelEntity_.queryChannel(history, this);
		mid_.channelEntity_.saveInput(this);
	}

	String createQueryString(Channel queryCh_) {
		String nameIsBlank = null;
		int j = 0;
		ArrayList<View> cmps = new ArrayList<View>();
		traversingComponents(tabBar_.getContentLayout(), cmps);
		for (View f : cmps) {
			// Only count input items, each of which matches an input form field.
			if (f instanceof mTextField) {
				mTextField tf = (mTextField) f;
				String value = tf.getText().toString().trim();
				if (value.equals(getString(R.string.touchinput))) {
					value = "";
				}
				ChannelParam par = (ChannelParam) queryCh_.params().elementAt(j);
				if ((par.fillType_ != null) && par.fillType_.equals("required") && value.trim().equals("")) {
					nameIsBlank = getString(R.string.pleaseInput1) + ((par.label_ == null) ? par.name_ : par.label_);
					break;
				}
				par.value_ = value;
				++j;
			} else if (f instanceof cCheckBox) {
				ChannelParam par = (ChannelParam) queryCh_.params().elementAt(j);
				cCheckBox cb = (cCheckBox) f;
				par.isChecked_ = cb.isChecked();
				if ((par.fillType_ != null) && par.fillType_.equals("required")) {
					if (!par.isChecked_) {
						nameIsBlank = getString(R.string.pleaseSelect)
								+ ((par.label_ == null) ? par.name_ : par.label_);
						break;
					}
				}
				++j;
			} else if (f instanceof Radio) {
				Radio radio = (Radio) f;
				ChannelParam par = (ChannelParam) queryCh_.params().elementAt(j);
				par.isChecked_ = radio.isChecked_;
				if ((par.fillType_ != null) && par.fillType_.equals("required")) {
					if (getSelectRadio(this, radio) == null) {
						nameIsBlank = getString(R.string.pleaseSelect) + par.name_;
						break;
					}
				}
				++j;
			} else if (f instanceof Select) {
				ChannelParam par = (ChannelParam) queryCh_.params().elementAt(j);
				Select select = (Select) f;
				par.value_ = (String) par.valuesV_.elementAt(select.currentMenu_ * 2 + 1);
				if ((par.fillType_ != null) && par.fillType_.equals("required") && par.value_.trim().equals("")) {
					nameIsBlank = getString(R.string.pleaseSelect) + ((par.label_ == null) ? par.name_ : par.label_);
					break;
				}
				++j;
			} else if (f instanceof Label) {
				if (((Label) f).isTagParse_)
					++j;
			}
		}
		return nameIsBlank;
	}

	/**
	 * 截获界面触摸事件
	 * */
	public boolean dispatchTouchEvent(MotionEvent event) {
		int touchEvent = event.getAction();
		int y = (int) event.getY();
		switch (touchEvent) {
		case MotionEvent.ACTION_DOWN:
			touchY_ = y;
			try {
				return super.dispatchTouchEvent(event);
			} catch (Exception e) {
				Utils.printException(e);
			}
		case MotionEvent.ACTION_UP:
			scrollView_ = null;
			return super.dispatchTouchEvent(event);
		case MotionEvent.ACTION_MOVE:
			if (scrollView_ != null) {
				scrollView_.scrollToY_ = touchY_ - y;
				scrollView_.onTouchEvent(event);
			}
			return super.dispatchTouchEvent(event);
		default:
			return super.dispatchTouchEvent(event);
		}

	}
	
	public void onDestory() {
		activities_.remove(this); // 把当前Activity从集合中移除
	}
	
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == UploadFile.NONE)
			return;
		// 拍照
		if (requestCode == UploadFile.PHOTOHRAPH) {
			// 设置文件保存路径这里放在跟目录下
			File picture = new File(Environment.getExternalStorageDirectory() + "/temp.jpg");
			startPhotoZoom(Uri.fromFile(picture));
		}

		if (data == null)
			return;

		// 读取相册缩放图片
		if (requestCode == UploadFile.PHOTOZOOM) {
			startPhotoZoom(data.getData());
		}
		// 处理结果
		if (requestCode == UploadFile.PHOTORESOULT) {
			Bundle extras = data.getExtras();
			try {
				if (extras != null) {
					Bitmap photo = extras.getParcelable("data");
					ByteArrayOutputStream stream = new ByteArrayOutputStream();
					// (0 - 100)压缩文件
					photo.compress(Bitmap.CompressFormat.PNG, 100, stream);
					UploadFile uploadFile = getUploadFile();
					if (null != uploadFile) {
						// 圆角处理
						photo = uploadFile.toRoundCorner(photo, 50);
						// 更新imageview
						uploadFile.imgView_.setImageBitmap(photo);
						// 保存视图到本地
						String localPath = uploadFile.storeImg(photo);
						// 上传
						uploadFile.upload(this, mid_, photo, localPath);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();

			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	/**
	 * 获取上传对象
	 * @return
	 */
	public UploadFile getUploadFile() {
		UploadFile temp = null;
		// 得到界面中层管理器子元素个数,从零开始计数
        final int sizeMid = vWidgetArray_.size();
        Object o = null;
        // 此循环处理当前form的联动
        for (int i = 0; i < sizeMid; i++) {
            // 得到界面中层管理框架中的单个子元素
            o = vWidgetArray_.elementAt(i);
          if (o instanceof UploadFile) {
        	  temp = (UploadFile)o;
			}
        }
        return temp;
	}
	
	/**
	 * 读取相册缩放图片
	 * @param uri
	 */
	public void startPhotoZoom(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, UploadFile.IMAGE_UNSPECIFIED);
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", 64);
		intent.putExtra("outputY", 64);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, UploadFile.PHOTORESOULT);
	}
	
	
}
